#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <arpa/inet.h>
#include "safecalls.h"
#include "networkinglib.h"

#define PROTOCOL "tcp"
#define REQUEST "GET / HTTP/1.0\n\n"

int main(int argc, char *argv[]) {
  int sockid, numbytes, result;
  char buf[250];
  char *words[3];
  char *port = "80";

  if (argc < 3) {
    printf("Usage: webclient host path [port]\n");
  }

  if (argc == 4) {
    port = argv[3];
  }

  signal(SIGUSR1, SIG_IGN); // turn off default safecalls error handling

  sockid = clientconnect(argv[1], port, PROTOCOL);
  if (sockid == -1) {
    fprintf(stderr, "\nUnable to connect to client.\n");
    exit(1);

  } else {

    /* The channel for communication to the server has now been established.
       Now, request the document  */

    sprintf(buf, "GET %s HTTP/1.0\n\n", argv[2]);
    result = write_buffer(sockid, buf, strlen(buf));
    if (result > 0) {

      /* Request has been sent.  Read the result and send all data to stdout. */

      result = copy(sockid, STDOUT_FILENO, 0);
      if (result < 0) {
        fprintf(stderr, "\nError downloading result.\n");      
      }
    } else {
      fprintf(stderr, "\nError sending request.\n");
    }

    close(sockid);

  }

  return 0;
}
